<template>
  <div class="resource-container">
    <h2>资源上传、下载和分享</h2>
    
    <!-- 文件上传区域 -->
    <el-upload
      class="upload-demo"
      drag
      action="https://jsonplaceholder.typicode.com/posts/"
      multiple
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      :on-error="handleError"
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div class="el-upload__tip"  v-slot：="tip">只能上传jpg/png文件，且不超过500kb</div>
    </el-upload>

    <!-- 文件列表区域 -->
    <el-table style="width: 100%; margin-top: 20px;">
      <el-table-column prop="name" label="文件名" width="180"></el-table-column>
      <el-table-column prop="size" label="大小" width="180"></el-table-column>
      <el-table-column label="操作">
        <template  v-slot:="scope">
          <el-button size="20" @click="downloadFile(scope.row)">下载</el-button>
          <el-button size="20" type="primary" @click="shareFile(scope.row)">分享</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  data() {
    return {

    };
  },
  methods: {
    handlePreview(file) {
      console.log('Preview file:', file);
      // 处理预览逻辑
    },
    handleRemove(file) {
      console.log('Remove file:', file);
      // 处理移除文件逻辑
    },
    beforeUpload(file) {
      const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt500K = file.size / 1024 < 500;

      if (!isJPGOrPNG) {
        this.$message.error('只能上传jpg/png文件');
      }
      if (!isLt500K) {
        this.$message.error('文件大小不能超过500kb');
      }

      return isJPGOrPNG &&isLt500K;
    },
    handleSuccess(response, file, fileList) {
      console.log('Upload success:', response, file, fileList);
      this.fileList.push({
        name: file.name,
        size: (file.size / 1024).toFixed(2) + ' KB',
        url: 'https://example.com/path/to/file/' + file.name // 替换为实际的文件URL
      });
      this.$message.success('文件上传成功');
    },
    handleError(err, file, fileList) {
      console.error('Upload error:', err, file, fileList);
      this.$message.error('文件上传失败');
    },
    downloadFile(file) {
      window.open(file.url, '_blank');
    },
    shareFile(file) {
      const shareUrl = file.url + '?share=true'; // 替换为实际的分享链接
      this.$message.success(`文件分享链接: ${shareUrl}`);
    }
  }
};
</script>

<style scoped>
.resource-container {
  max-width: 1300px;
  margin: 0 auto;
  padding: 20px;
  margin-left: 180px;
  background-color: rgba(186, 205, 113, 0.074);
}

.upload-demo {
  margin-bottom: 20px;
}
</style>
